<?php
/**
 * Created by PhpStorm.
 * User: edmmss
 * Date: 2021/10/1
 * Time: 15:11
 */

namespace Edmmss\Easyswoole\Task\Client;

use Yii;
use Edmmss\Easyswoole\Task\Consts\TaskConst;

class RpcRequest
{
    /**
     * Yii2框架请求方法
     *
     * @date   2021/10/1
     * @param $call
     * @param $taskType
     * @param $data
     * @return array|void
     * @throws \Exception
     * @author edmmss
     */
    public function yiiRequest($call, $taskType, $data)
    {
        /* @var Client $taskRpcClient */
        $taskRpcClient = Yii::$app->taskRpcClient;
        $response = $taskRpcClient->request($call, $taskType, $data);

        return $this->handle($response);
    }

    /**
     * 处理返回操作
     *
     * @date   2021/10/1
     * @param Response $response
     * @return array|void
     * @author edmmss
     */
    private function handle(Response $response)
    {
        if ($response->getIsSuccess()) {
            // 请求返回成功
            return $response->getData();
        } else {
            // 请求返回失败，直接返回错误json字符串
            if ($response->isLogicError()) {
                // rpc主动报错的错误信息
                $data = [
                    'errorCode'    => (int)$response->getErrorCode(),
                    'errorMessage' => (string)$response->getErrorMessage(),
                    'data'         => (object)[],
                ];
            } else {
                // 一些其他错误，如连接超时等
                $data = $response->getError();
            }

            echo json_encode($data);
            exit;
        }
    }
}